<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 会员卡申请追加
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m310030_000012_t_trade_card_order extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%trade}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%trade}}')->andWhere(['bizno' => 'card2']);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            $cardorder = (new Query())->from('{{%card_order}}')->andWhere([
                'trade_id' => $row['id']
            ])->one();
            if (!$cardorder) {
                $cardorder = (new Query())->from('{{%card_order}}')->andWhere([
                    'expired_at' => $row['unified_no']
                ])->one();
            }
            if (!$cardorder) {
                continue;
            }
            $connect->update($migration->tableName, [
                'unified_no' => $cardorder['order_no'],
                'bizno' => 'card',
            ], [
                'id' => $row['id']
            ])->execute();
        }
    }

}
